from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from myadmin.models import Member
from datetime import datetime
from myadmin.models import Shop, Category, Product, Orders, Payment, OrderDetail
from django.http import HttpResponse, JsonResponse


# Create your views here.


def index(request):
    # 移动端首页
    # 获取并判断当前店铺信息
    shopinfo = request.session.get('shopinfo', None)
    if shopinfo is None:
        return redirect(reverse("mobile_shop"))
    # 获取当前店铺下的菜品类别和菜品信息
    clist = Category.objects.filter(shop_id=shopinfo['id'], status=1)
    productlist = dict()
    for vo in clist:
        plist = Product.objects.filter(category_id=vo.id, status=1)
        productlist[vo.id] = plist
    context = {'categorylist': clist, 'productlist': productlist.items(), 'cid': clist[0]}
    return render(request, "mobile/index.html", context)


def register(request):
    # 移动端会员注册/登录表单
    return render(request, "mobile/register.html")


def doRegister(request):
    # 执行会员注册/登录
    verifycode = "1234"  # request.session['verifycode']
    if verifycode != request.POST['code']:
        context = {"info": '验证码错误'}
        return render(request, "mobile/register.html", context)
    try:
        # 根据手机号码获取当前会员信息
        member = Member.objects.get(mobile=request.POST['mobile'])

    except Exception as err:
        # 执行当前会员注册
        print(err)
        ob = Member()
        ob.nickname = "顾客"
        ob.avatar = "moren.png"
        ob.mobile = request.POST['mobile']
        ob.status = '1'
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
    # 检验当前会员状态
    member = Member.objects.get(mobile=request.POST['mobile'])
    if member.status == 1 or member.status == '1':
        # 将当前会员信息转成字典格式并保存到session中
        request.session['mobileuser'] = member.toDict()
        return redirect(reverse("mobile_index"))
    else:
        context = {"info": "此账户信息禁用！"}
        return render(request, "mobile/register.html", context)


def shop(request):
    # 移动端选择店铺页面
    context = {"shoplist": Shop.objects.filter(status=1)}
    return render(request, "mobile/shop.html", context)


def selectShop(request):
    # 执行移动端店铺选择操作
    # 获取选择的店铺信息，并放置到session中
    sid = request.GET['sid']
    ob = Shop.objects.get(id=sid)
    request.session['shopinfo'] = ob.toDict()
    request.session['mobile_cartlist'] = {}
    # 跳转到首页
    return redirect(reverse("mobile_index"))


def addOrders(request):
    # 移动端下单页面
    cartlist = request.session.get('mobile_cartlist', {})
    # if cartlist == {}:
    #     return HttpResponse(
    #         "<script>window.alert('未找到对应信息');window.location.href = \"{% url 'mobile_selectshop' %}\";</script>")
    total_money = 0  # 初始化总金额
    for vo in cartlist:
        total_money += cartlist[vo]['num'] * cartlist[vo]['price']
    request.session['mobile_total_money'] = total_money
    # context = {'categorylist': request.session.get("categorylist", {}).items(),
    #            'cartlist': request.session.get("cartlist", {}).items()}
    return render(request, "mobile/addOrders.html")


def doAddOrders(request):
    # 执行订单添加
    try:
        # 执行订单信息的添加
        od = Orders()
        od.shop_id = request.session['shopinfo']['id']
        od.member_id = request.session['mobileuser']['id']
        od.user_id = 0
        od.money = request.session['mobile_total_money']
        od.status = 1  # 订单状态:1过行中/2无效/3已完成
        od.payment_status = 2  # 支付状态:1未支付/2已支付/3已退款
        od.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        od.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        od.save()
        print(1111, od)
        # 执行支付信息添加
        op = Payment()
        op.order_id = od.id
        op.member_id = request.session['mobileuser']['id']
        op.money = request.session['mobile_total_money']
        op.type = request.GET.get('ptype', 1)  # 付款方式：1会员付款/2收银收款
        op.bank = request.GET.get('bank', 3)  # 收款银行渠道:1微信/2余额/3现金/4支付宝
        op.status = 2  # 支付状态:1未支付/2已支付/3已退款
        op.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        op.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        op.save()

        # 执行订单详情添加
        cartlist = request.session.get("mobile_cartlist", {})  # 获取购物车中的菜品信息
        for item in cartlist.values():
            ov = OrderDetail()
            ov.order_id = od.id
            ov.product_id = item['id']
            ov.product_name = item['name']
            ov.price = item['price']
            ov.quantity = item['num']
            ov.status = 1
            ov.save()
        request.session['mobile_cartlist'] = {}
        request.session['mobile_total_money'] = {}
        context = {'order': od}
        return render(request, "mobile/orderinfo.html", context)
    except Exception as err:
        print(222, err)
